home *** CD-ROM | disk | FTP | other *** search
/ Aminet 3 / Aminet 3 - July 1994.iso / Aminet / mus / misc / mpegaudio.lha / mpegaudio / musicin.c < prev    next >
C/C++ Source or Header  |  1994-03-21  |  39KB  |  1,016 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. musicin.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress              *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
  10.  *                                                                    *
  11.  * VERSION 4.0                                                        *
  12.  *   changes made since last update:                                  *
  13.  *   date   programmers         comment                               *
  14.  * 3/01/91  Douglas Wong,       start of version 1.1 records          *
  15.  *          Davis Pan                                                 *
  16.  * 3/06/91  Douglas Wong,       rename: setup.h to endef.h            *
  17.  *                              removed extraneous variables          *
  18.  * 3/21/91  J.Georges Fritsch   introduction of the bit-stream        *
  19.  *                              package. This package allows you      *
  20.  *                              to generate the bit-stream in a       *
  21.  *                              binary or ascii format                *
  22.  * 3/31/91  Bill Aspromonte     replaced the read of the SB matrix    *
  23.  *                              by an "code generated" one            *
  24.  * 5/10/91  W. Joseph Carter    Ported to Macintosh and Unix.         *
  25.  *                              Incorporated Jean-Georges Fritsch's   *
  26.  *                              "bitstream.c" package.                *
  27.  *                              Modified to strictly adhere to        *
  28.  *                              encoded bitstream specs, including    *
  29.  *                              "Berlin changes".                     *
  30.  *                              Modified user interface dialog & code *
  31.  *                              to accept any input & output          *
  32.  *                              filenames desired.  Also added        *
  33.  *                              de-emphasis prompt and final bail-out *
  34.  *                              opportunity before encoding.          *
  35.  *                              Added AIFF PCM sound file reading     *
  36.  *                              capability.                           *
  37.  *                              Modified PCM sound file handling to   *
  38.  *                              process all incoming samples and fill *
  39.  *                              out last encoded frame with zeros     *
  40.  *                              (silence) if needed.                  *
  41.  *                              Located and fixed numerous software   *
  42.  *                              bugs and table data errors.           *
  43.  * 27jun91  dpwe (Aware Inc)    Used new frame_params struct.         *
  44.  *                              Clear all automatic arrays.           *
  45.  *                              Changed some variable names,          *
  46.  *                              simplified some code.                 *
  47.  *                              Track number of bits actually sent.   *
  48.  *                              Fixed padding slot, stereo bitrate    *
  49.  *                              Added joint-stereo : scales L+R.      *
  50.  * 6/12/91  Earle Jennings      added fix for MS_DOS in obtain_param  *
  51.  * 6/13/91  Earle Jennings      added stack length adjustment before  *
  52.  *                              main for MS_DOS                       *
  53.  * 7/10/91  Earle Jennings      conversion of all float to FLOAT      *
  54.  *                              port to MsDos from MacIntosh completed*
  55.  * 8/ 8/91  Jens Spille         Change for MS-C6.00                   *
  56.  * 8/22/91  Jens Spille         new obtain_parameters()               *
  57.  *10/ 1/91  S.I. Sudharsanan,   Ported to IBM AIX platform.           *
  58.  *          Don H. Lee,                                               *
  59.  *          Peter W. Farrett                                          *
  60.  *10/ 3/91  Don H. Lee          implemented CRC-16 error protection   *
  61.  *                              newly introduced functions are        *
  62.  *                              I_CRC_calc, II_CRC_calc and encode_CRC*
  63.  *                              Additions and revisions are marked    *
  64.  *                              with "dhl" for clarity                *
  65.  *11/11/91 Katherine Wang       Documentation of code.                *
  66.  *                                (variables in documentation are     *
  67.  *                                surround by the # symbol, and an '*'*
  68.  *                                denotes layer I or II versions)     *
  69.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  70.  *                              important fixes involved changing     *
  71.  *                              16-bit ints to long or unsigned in    *
  72.  *                              bit alloc routines for quant of 65535 *
  73.  *                              and passing proper function args.     *
  74.  *                              Removed "Other Joint Stereo" option   *
  75.  *                              and made bitrate be total channel     *
  76.  *                              bitrate, irrespective of the mode.    *
  77.  *                              Fixed many small bugs & reorganized.  *
  78.  * 2/25/92  Masahiro Iwadare    made code cleaner and more consistent *
  79.  * 8/07/92  Mike Coleman        make exit() codes return error status *
  80.  *                              made slight changes for portability   *
  81.  *19 aug 92 Soren H. Nielsen    Changed MS-DOS file name extensions.  *
  82.  * 8/25/92  Shaun Astarabadi    Replaced rint() function with explicit*
  83.  *                              rounding for portability with MSDOS.  *
  84.  * 9/22/92  jddevine@aware.com  Fixed _scale_factor_calc() calls.     *
  85.  *10/19/92  Masahiro Iwadare    added info->mode and info->mode_ext   *
  86.  *                              updates for AIFF format files         *
  87.  * 3/10/93  Kevin Peterson      In parse_args, only set non default   *
  88.  *                              bit rate if specified in arg list.    *
  89.  *                              Use return value from aiff_read_hdrs  *
  90.  *                              to fseek to start of sound data       *
  91.  * 7/26/93  Davis Pan           fixed bug in printing info->mode_ext  *
  92.  *                              value for joint stereo condition      *
  93.  * 8/27/93 Seymour Shlien,      Fixes in Unix and MSDOS ports,        *
  94.  *         Daniel Lauzon, and                                         *
  95.  *         Bill Truerniet                                             *
  96.  **********************************************************************/
  97.  
  98. #ifdef MS_DOS
  99. #include <dos.h>
  100. #endif
  101. #include "common.h"
  102. #include "encoder.h"
  103.  
  104. #ifdef UNIX
  105. #include <time.h>
  106. #endif
  107.  
  108. /* Global variable definitions for "musicin.c" */
  109.  
  110. FILE               *musicin;
  111. Bit_stream_struc   bs;
  112. char               *programName;
  113.  
  114. /* Implementations */
  115.  
  116. /************************************************************************
  117. /*
  118. /* obtain_parameters
  119. /*
  120. /* PURPOSE:  Prompts for and reads user input for encoding parameters
  121. /*
  122. /* SEMANTICS:  The parameters read are:
  123. /* - input and output filenames
  124. /* - sampling frequency (if AIFF file, will read from the AIFF file header)
  125. /* - layer number
  126. /* - mode (stereo, joint stereo, dual channel or mono)
  127. /* - psychoacoustic model (I or II)
  128. /* - total bitrate, irrespective of the mode
  129. /* - de-emphasis, error protection, copyright and original or copy flags
  130. /*
  131. /************************************************************************/
  132.  
  133. void
  134. obtain_parameters(fr_ps,psy,num_samples,original_file_name,encoded_file_name)
  135. frame_params    *fr_ps;
  136. int             *psy;
  137. unsigned long   *num_samples;
  138. char            original_file_name[MAX_NAME_SIZE];
  139. char            encoded_file_name[MAX_NAME_SIZE];
  140. {
  141.     int j;
  142.     long int freq;
  143.     int model, brt;
  144.     char t[50];
  145.     IFF_AIFF pcm_aiff_data;
  146.     layer *info = fr_ps->header;
  147.     long soundPosition;
  148.  
  149.     do  {
  150.        printf("Enter PCM input file name <required>: ");
  151.        gets(original_file_name);
  152.        if (original_file_name[0] == NULL_CHAR)
  153.        printf("PCM input file name is required.\n");
  154.     } while (original_file_name[0] == NULL_CHAR);
  155.     printf(">>> PCM input file name is: %s\n", original_file_name);
  156.  
  157.     if ((musicin = fopen(original_file_name, "rb")) == NULL) {
  158.        printf("Could not find \"%s\".\n", original_file_name);
  159.        exit(1);
  160.     }
  161.  
  162. #ifdef  MS_DOS
  163.     printf("Enter MPEG encoded output file name <%s>: ",
  164.            new_ext(original_file_name, DFLT_EXT)); /* 92-08-19 shn */
  165. #else
  166.     printf("Enter MPEG encoded output file name <%s%s>: ",
  167.            original_file_name, DFLT_EXT);
  168. #endif
  169.  
  170.     gets(encoded_file_name);
  171.     if (encoded_file_name[0] == NULL_CHAR) {
  172. #ifdef  MS_DOS
  173.         /* replace old extension with new one, 92-08-19 shn */
  174.         strcpy(encoded_file_name,new_ext(original_file_name, DFLT_EXT));
  175. #else
  176.         strcat(strcpy(encoded_file_name, original_file_name), DFLT_EXT);
  177. #endif
  178.     }
  179.         
  180.  
  181.     printf(">>> MPEG encoded output file name is: %s\n", encoded_file_name);
  182.  
  183.     open_bit_stream_w(&bs, encoded_file_name, BUFFER_SIZE);
  184.  
  185.     if ((soundPosition = aiff_read_headers(musicin, &pcm_aiff_data)) != -1) {
  186.  
  187.        printf(">>> Using Audio IFF sound file headers\n");
  188.  
  189.        aiff_check(original_file_name, &pcm_aiff_data);
  190.  
  191.        if (fseek(musicin, soundPosition, SEEK_SET) != 0) {
  192.           printf("Could not seek to PCM sound data in \"%s\".\n",
  193.                  original_file_name);
  194.           exit(1);
  195.        }
  196.  
  197.        info->sampling_frequency = SmpFrqIndex((long)pcm_aiff_data.sampleRate);
  198.        printf(">>> %.f Hz sampling frequency selected\n",
  199.               pcm_aiff_data.sampleRate);
  200.  
  201.        /* Determine number of samples in sound file */
  202. #ifndef MS_DOS
  203.        *num_samples = pcm_aiff_data.numChannels *
  204.                       pcm_aiff_data.numSampleFrames;
  205. #else
  206.        *num_samples = (long)(pcm_aiff_data.numChannels) *
  207.                       (long)(pcm_aiff_data.numSampleFrames);
  208. #endif
  209.  
  210.     }
  211.     else {    /* Not using Audio IFF sound file headers. */
  212.  
  213.        printf("What is the sampling frequency? <44100>[Hz]: ");
  214.        gets(t);
  215.        freq = atol(t);
  216.        switch (freq) {
  217.           case 48000 : info->sampling_frequency = 1;
  218.               printf(">>> %ld Hz sampling freq selected\n", freq);
  219.               break;
  220.           case 44100 : info->sampling_frequency = 0;
  221.               printf(">>> %ld Hz sampling freq selected\n", freq);
  222.               break;
  223.           case 32000 : info->sampling_frequency = 2;
  224.               printf(">>> %ld Hz sampling freq selected\n", freq);
  225.               break;
  226.           default:    info->sampling_frequency = 0;
  227.               printf(">>> Default 44.1 kHz samp freq selected\n");
  228.        }
  229.  
  230.        if (fseek(musicin, 0, SEEK_SET) != 0) {
  231.           printf("Could not seek to PCM sound data in \"%s\".\n",
  232.                   original_file_name);
  233.           exit(1);
  234.        }
  235.  
  236.        /* Declare sound file to have "infinite" number of samples. */
  237.        *num_samples = MAX_U_32_NUM;
  238.  
  239.     }
  240.  
  241.     printf("Which layer do you want to use?\n");
  242.     printf("Available: Layer (1), Layer (<2>): ");
  243.     gets(t);
  244.     switch(*t){
  245.        case '1': info->lay = 1; printf(">>> Using Layer %s\n",t); break;
  246.        case '2': info->lay = 2; printf(">>> Using Layer %s\n",t); break;
  247.        default:  info->lay = 2; printf(">>> Using default Layer 2\n"); break;
  248.     }
  249.  
  250.     printf("Which mode do you want?\n");
  251.     printf("Available: (<s>)tereo, (j)oint stereo, ");
  252.     printf("(d)ual channel, s(i)ngle Channel: ");
  253.     gets(t);
  254.     switch(*t){
  255.        case 's':
  256.        case 'S':
  257.           info->mode = MPG_MD_STEREO; info->mode_ext = 0;
  258.           printf(">>> Using mode %s\n",t);
  259.           break;
  260.        case 'j':
  261.        case 'J':
  262.           info->mode = MPG_MD_JOINT_STEREO;
  263.           printf(">>> Using mode %s\n",t);
  264.           break;
  265.        case 'd':
  266.        case 'D':
  267.           info->mode = MPG_MD_DUAL_CHANNEL; info->mode_ext = 0;
  268.           printf(">>> Using mode %s\n",t);
  269.           break;
  270.        case 'i':
  271.        case 'I':
  272.           info->mode = MPG_MD_MONO; info->mode_ext = 0;
  273.           printf(">>> Using mode %s\n",t);
  274.           break;
  275.        default:
  276.           info->mode = MPG_MD_STEREO; info->mode_ext = 0;
  277.           printf(">>> Using default stereo mode\n");
  278.           break;
  279.     }
  280.  
  281.     printf("Which psychoacoustic model do you want to use? <2>: ");
  282.     gets(t);
  283.     model = atoi(t);
  284.     if (model > 2 || model < 1) {
  285.        printf(">>> Default model 2 selected\n");
  286.        *psy = 2;
  287.     }
  288.     else {
  289.        *psy = model;
  290.        printf(">>> Using psychoacoustic model %d\n", model);
  291.     }
  292.  
  293.     printf("What is the total bitrate? <%u>[kbps]: ", DFLT_BRT);
  294.     gets(t);
  295.     brt = atoi(t);
  296.     if (brt == 0) brt = -10;
  297.     j=0;
  298.     while (j<15) {
  299.        if (bitrate[info->lay-1][j] == brt) break;
  300.        j++;
  301.     }
  302.     if (j==15) {
  303.        printf(">>> Using default %u kbps\n", DFLT_BRT);
  304.        for (j=0;j<15;j++)
  305.           if (bitrate[info->lay-1][j] == DFLT_BRT) {
  306.              info->bitrate_index = j;
  307.              break;
  308.           }
  309.     }
  310.     else{
  311.        info->bitrate_index = j;
  312.        printf(">>> Bitrate = %d kbps\n", bitrate[info->lay-1][j]);
  313.     }
  314.  
  315.     printf("What type of de-emphasis should the decoder use?\n");
  316.     printf("Available: (<n>)one, (5)0/15 microseconds, (c)citt j.17: ");
  317.     gets(t);
  318.     if (*t != 'n' && *t != '5' && *t != 'c') {
  319.        printf(">>> Using default no de-emphasis\n");
  320.        info->emphasis = 0;
  321.     }
  322.     else {
  323.        if (*t == 'n')      info->emphasis = 0;
  324.        else if (*t == '5') info->emphasis = 1;
  325.        else if (*t == 'c') info->emphasis = 3;
  326.        printf(">>> Using de-emphasis %s\n",t);
  327.     }
  328.  
  329. /*  Start 2. Part changes for CD Ver 3.2; jsp; 22-Aug-1991 */
  330.  
  331.     printf("Do you want to set the private bit? (y/<n>): ");
  332.     gets(t);
  333.     if (*t == 'y' || *t == 'Y') info->extension = 1;
  334.     else                        info->extension = 0;
  335.     if(info->extension) printf(">>> Private bit set\n");
  336.     else                printf(">>> Private bit not set\n");
  337.  
  338. /*  End changes for CD Ver 3.2; jsp; 22-Aug-1991 */
  339.  
  340.     printf("Do you want error protection? (y/<n>): ");
  341.     gets(t);
  342.     if (*t == 'y' || *t == 'Y') info->error_protection = TRUE;
  343.     else                        info->error_protection = FALSE;
  344.     if(info->error_protection) printf(">>> Error protection used\n");
  345.     else printf(">>> Error protection not used\n");
  346.  
  347.     printf("Is the material copyrighted? (y/<n>): ");
  348.     gets(t);
  349.     if (*t == 'y' || *t == 'Y') info->copyright = 1;
  350.     else                        info->copyright = 0;
  351.     if(info->copyright) printf(">>> Copyrighted material\n");
  352.     else                printf(">>> Material not copyrighted\n");
  353.  
  354.     printf("Is this the original? (y/<n>): ");
  355.     gets(t);
  356.     if (*t == 'y' || *t == 'Y') info->original = 1;
  357.     else                        info->original = 0;
  358.     if(info->original) printf(">>> Original material\n");
  359.     else               printf(">>> Material not original\n");
  360.  
  361.     printf("Do you wish to exit (last chance before encoding)? (y/<n>): ");
  362.     gets(t);
  363.     if (*t == 'y' || *t == 'Y') exit(0);
  364. }
  365.  
  366. /************************************************************************
  367. /*
  368. /* parse_args
  369. /*
  370. /* PURPOSE:  Sets encoding parameters to the specifications of the
  371. /* command line.  Default settings are used for parameters
  372. /* not specified in the command line.
  373. /*
  374. /* SEMANTICS:  The command line is parsed according to the following
  375. /* syntax:
  376. /*
  377. /* -l  is followed by the layer number
  378. /* -m  is followed by the mode
  379. /* -p  is followed by the psychoacoustic model number
  380. /* -s  is followed by the sampling rate
  381. /* -b  is followed by the total bitrate, irrespective of the mode
  382. /* -d  is followed by the emphasis flag
  383. /* -c  is followed by the copyright/no_copyright flag
  384. /* -o  is followed by the original/not_original flag
  385. /* -e  is followed by the error_protection on/off flag
  386. /*
  387. /* If the input file is in AIFF format, the sampling frequency is read
  388. /* from the AIFF header.
  389. /*
  390. /* The input and output filenames are read into #inpath# and #outpath#.
  391. /*
  392. /************************************************************************/
  393.  
  394. void
  395. parse_args(argc, argv, fr_ps, psy, num_samples, inPath, outPath)
  396. int     argc;
  397. char    **argv;
  398. frame_params  *fr_ps;
  399. int     *psy;
  400. unsigned long *num_samples;
  401. char    inPath[MAX_NAME_SIZE];
  402. char    outPath[MAX_NAME_SIZE];
  403. {
  404.    FLOAT srate;
  405.    int   brate;
  406.    layer *info = fr_ps->header;
  407.    int   err = 0, i = 0;
  408.    IFF_AIFF pcm_aiff_data;
  409.    long samplerate;
  410.    long soundPosition;
  411.  
  412.    /* preset defaults */
  413.    inPath[0] = '\0';   outPath[0] = '\0';
  414.    info->lay = DFLT_LAY;
  415.    switch(DFLT_MOD) {
  416.       case 's': info->mode = MPG_MD_STEREO; info->mode_ext = 0; break;
  417.       case 'd': info->mode = MPG_MD_DUAL_CHANNEL; info->mode_ext=0; break;
  418.       case 'j': info->mode = MPG_MD_JOINT_STEREO; break;
  419.       case 'm': info->mode = MPG_MD_MONO; info->mode_ext = 0; break;
  420.       default:
  421.          fprintf(stderr, "%s: Bad mode dflt %c\n", programName, DFLT_MOD);
  422.          abort();
  423.    }
  424.    *psy = DFLT_PSY;
  425.    if((info->sampling_frequency = SmpFrqIndex((long)(1000*DFLT_SFQ))) < 0) {
  426.       fprintf(stderr, "%s: bad sfrq default %.2f\n", programName, DFLT_SFQ);
  427.       abort();
  428.    }
  429.    if((info->bitrate_index = BitrateIndex(info->lay, DFLT_BRT)) < 0) {
  430.       fprintf(stderr, "%s: bad default bitrate %u\n", programName, DFLT_BRT);
  431.       abort();
  432.    }
  433.    switch(DFLT_EMP) {
  434.       case 'n': info->emphasis = 0; break;
  435.       case '5': info->emphasis = 1; break;
  436.       case 'c': info->emphasis = 3; break;
  437.       default: 
  438.          fprintf(stderr, "%s: Bad emph dflt %c\n", programName, DFLT_EMP);
  439.          abort();
  440.    }
  441.    info->copyright = 0; info->original = 0; info->error_protection = FALSE;
  442.  
  443.    /* process args */
  444.    while(++i<argc && err == 0) {
  445.       char c, *token, *arg, *nextArg;
  446.       int  argUsed;
  447.  
  448.       token = argv[i];
  449.       if(*token++ == '-') {
  450.          if(i+1 < argc) nextArg = argv[i+1];
  451.          else           nextArg = "";
  452.          argUsed = 0;
  453.          while(c = *token++) {
  454.             if(*token /* NumericQ(token) */) arg = token;
  455.             else                             arg = nextArg;
  456.             switch(c) {
  457.                case 'l':        info->lay = atoi(arg); argUsed = 1;
  458.                   if(info->lay<1 || info->lay>2) {
  459.                      fprintf(stderr,"%s: -l layer must be 1 or 2, not %s\n",
  460.                           programName, arg);
  461.                      err = 1;
  462.                   }
  463.                   break;
  464.                case 'm':        argUsed = 1;
  465.                   if (*arg == 's')
  466.                     { info->mode = MPG_MD_STEREO; info->mode_ext = 0; }
  467.                   else if (*arg == 'd')
  468.                     { info->mode = MPG_MD_DUAL_CHANNEL; info->mode_ext=0; }
  469.                   else if (*arg == 'j')
  470.                     { info->mode = MPG_MD_JOINT_STEREO; }
  471.                   else if (*arg == 'm')
  472.                     { info->mode = MPG_MD_MONO; info->mode_ext = 0; }
  473.                   else {
  474.                     fprintf(stderr,"%s: -m mode must be s/d/j/m not %s\n",
  475.                             programName, arg);
  476.                     err = 1;
  477.                   }
  478.                   break;
  479.                case 'p':        *psy = atoi(arg); argUsed = 1;
  480.                   if(*psy<1 || *psy>2) {
  481.                      fprintf(stderr,"%s: -p model must be 1 or 2, not %s\n",
  482.                              programName, arg);
  483.                      err = 1;
  484.                   }
  485.                   break;
  486.  
  487.                case 's':
  488.                   argUsed = 1;
  489.                   srate = atof( arg );
  490.                   /* samplerate = rint( 1000.0 * srate ); $A  */
  491.                   samplerate = (long) (( 1000.0 * srate ) + 0.5);
  492.                   if( (info->sampling_frequency = SmpFrqIndex((long) samplerate)) < 0 )
  493.                       err = 1;
  494.                   break;
  495.                   
  496.                case 'b':        
  497.              argUsed = 1;
  498.           brate = atoi(arg); 
  499.           if( (info->bitrate_index = BitrateIndex(info->lay, brate)) < 0)
  500.              err=1;                  
  501.          break;
  502.                case 'd':        argUsed = 1;
  503.                   if (*arg == 'n')                    info->emphasis = 0;
  504.                   else if (*arg == '5')               info->emphasis = 1;
  505.                   else if (*arg == 'c')               info->emphasis = 3;
  506.                   else {
  507.                      fprintf(stderr,"%s: -d emp must be n/5/c not %s\n",
  508.                              programName, arg);
  509.                      err = 1;
  510.                   }
  511.                   break;
  512.                 case 'c':       info->copyright = 1; break;
  513.                 case 'o':       info->original  = 1; break;
  514.                 case 'e':       info->error_protection = TRUE; break;
  515.                 default:        fprintf(stderr,"%s: unrec option %c\n",
  516.                                         programName, c);
  517.                                 err = 1; break;
  518.             }
  519.             if(argUsed) {
  520.                if(arg == token)    token = "";   /* no more from token */
  521.                else                ++i;          /* skip arg we used */
  522.                arg = ""; argUsed = 0;
  523.             }
  524.          }
  525.       }
  526.       else {
  527.          if(inPath[0] == '\0')       strcpy(inPath, argv[i]);
  528.          else if(outPath[0] == '\0') strcpy(outPath, argv[i]);
  529.          else {
  530.             fprintf(stderr,"%s: excess arg %s\n", programName, argv[i]);
  531.             err = 1;
  532.          }
  533.       }
  534.    }
  535.  
  536.    if(err || inPath[0] == '\0') usage();  /* never returns */
  537.  
  538.    if(outPath[0] == '\0') {
  539.       strcpy(outPath, inPath);
  540.       strcat(outPath, DFLT_EXT);
  541.    }
  542.  
  543.    if ((musicin = fopen(inPath, "rb")) == NULL) {
  544.       printf("Could not find \"%s\".\n", inPath);
  545.       exit(1);
  546.    }
  547.  
  548.    open_bit_stream_w(&bs, outPath, BUFFER_SIZE);
  549.  
  550.    if ((soundPosition = aiff_read_headers(musicin, &pcm_aiff_data)) != -1) {
  551.  
  552.       printf(">>> Using Audio IFF sound file headers\n");
  553.  
  554.       aiff_check(inPath, &pcm_aiff_data);
  555.  
  556.       if (fseek(musicin, soundPosition, SEEK_SET) != 0) {
  557.          printf("Could not seek to PCM sound data in \"%s\".\n", inPath);
  558.          exit(1);
  559.       }
  560.  
  561.       info->sampling_frequency = SmpFrqIndex((long)pcm_aiff_data.sampleRate);
  562.       printf(">>> %.f Hz sampling frequency selected\n",
  563.              pcm_aiff_data.sampleRate);
  564.  
  565.       /* Determine number of samples in sound file */
  566. #ifndef MS_DOS
  567.       *num_samples = pcm_aiff_data.numChannels *
  568.                      pcm_aiff_data.numSampleFrames;
  569. #else
  570.       *num_samples = (long)(pcm_aiff_data.numChannels) *
  571.                      (long)(pcm_aiff_data.numSampleFrames);
  572. #endif
  573.       if ( pcm_aiff_data.numChannels == 1 ) {
  574.         info->mode = MPG_MD_MONO;
  575.         info->mode_ext = 0;
  576.       }
  577.    }
  578.    else {    /* Not using Audio IFF sound file headers. */
  579.  
  580.       if (fseek(musicin, 0, SEEK_SET) != 0) {
  581.          printf("Could not seek to PCM sound data in \"%s\".\n", inPath);
  582.          exit(1);
  583.       }
  584.  
  585.       /* Declare sound file to have "infinite" number of samples. */
  586.       *num_samples = MAX_U_32_NUM;
  587.  
  588.    }
  589.  
  590. }
  591.  
  592. /************************************************************************
  593. /*
  594. /* print_config
  595. /*
  596. /* PURPOSE:  Prints the encoding parameters used
  597. /*
  598. /************************************************************************/
  599.  
  600. void
  601. print_config(fr_ps, psy, num_samples, inPath, outPath)
  602. frame_params *fr_ps;
  603. int     *psy;
  604. unsigned long *num_samples;
  605. char    inPath[MAX_NAME_SIZE];
  606. char    outPath[MAX_NAME_SIZE];
  607. {
  608.  layer *info = fr_ps->header;
  609.  
  610.    printf("Encoding configuration:\n");
  611.    if(info->mode != MPG_MD_JOINT_STEREO)
  612.       printf("Layer=%s   mode=%s   extn=%d   psy model=%d\n",
  613.              layer_names[info->lay-1], mode_names[info->mode],
  614.              info->mode_ext, *psy);
  615.    else printf("Layer=%s   mode=%s   extn=data dependant   psy model=%d\n",
  616.                layer_names[info->lay-1], mode_names[info->mode], *psy);
  617.    printf("samp frq=%.1f kHz   total bitrate=%d kbps\n",
  618.           s_freq[info->sampling_frequency],
  619.           bitrate[info->lay-1][info->bitrate_index]);
  620.    printf("de-emph=%d   c/right=%d   orig=%d   errprot=%d\n",
  621.           info->emphasis, info->copyright, info->original,
  622.           info->error_protection);
  623.    printf("input file: '%s'   output file: '%s'\n", inPath, outPath);
  624. }
  625.  
  626. /************************************************************************
  627. /*
  628. /* main
  629. /*
  630. /* PURPOSE:  MPEG I Encoder supporting layers 1 and 2, and
  631. /* psychoacoustic models 1 (MUSICAM) and 2 (AT&T)
  632. /*
  633. /* SEMANTICS:  One overlapping frame of audio of up to 2 channels are
  634. /* processed at a time in the following order:
  635. /* (associated routines are in parentheses)
  636. /*
  637. /* 1.  Filter sliding window of data to get 32 subband
  638. /* samples per channel.
  639. /* (window_subband,filter_subband)
  640. /*
  641. /* 2.  If joint stereo mode, combine left and right channels
  642. /* for subbands above #jsbound#.
  643. /* (*_combine_LR)
  644. /*
  645. /* 3.  Calculate scalefactors for the frame, and if layer 2,
  646. /* also calculate scalefactor select information.
  647. /* (*_scale_factor_calc)
  648. /*
  649. /* 4.  Calculate psychoacoustic masking levels using selected
  650. /* psychoacoustic model.
  651. /* (*_Psycho_One, psycho_anal)
  652. /*
  653. /* 5.  Perform iterative bit allocation for subbands with low
  654. /* mask_to_noise ratios using masking levels from step 4.
  655. /* (*_main_bit_allocation)
  656. /*
  657. /* 6.  If error protection flag is active, add redundancy for
  658. /* error protection.
  659. /* (*_CRC_calc)
  660. /*
  661. /* 7.  Pack bit allocation, scalefactors, and scalefactor select
  662. /* information (layer 2) onto bitstream.
  663. /* (*_encode_bit_alloc,*_encode_scale,II_transmission_pattern)
  664. /*
  665. /* 8.  Quantize subbands and pack them into bitstream
  666. /* (*_subband_quantization, *_sample_encoding)
  667. /*
  668. /************************************************************************/
  669.  
  670. main(argc, argv)
  671. int     argc;
  672. char    **argv;
  673. {
  674. typedef double SBS[2][3][SCALE_BLOCK][SBLIMIT];
  675.     SBS  FAR        *sb_sample;
  676. typedef double JSBS[3][SCALE_BLOCK][SBLIMIT];
  677.     JSBS FAR        *j_sample;
  678. typedef double IN[2][HAN_SIZE];
  679.     IN   FAR        *win_que;
  680. typedef unsigned int SUB[2][3][SCALE_BLOCK][SBLIMIT];
  681.     SUB  FAR        *subband;
  682.  
  683.     frame_params fr_ps;
  684.     layer info;
  685.     char original_file_name[MAX_NAME_SIZE];
  686.     char encoded_file_name[MAX_NAME_SIZE];
  687.     short FAR **win_buf;
  688. static short FAR buffer[2][1152];
  689. static unsigned int bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT];
  690. static unsigned int scalar[2][3][SBLIMIT], j_scale[3][SBLIMIT];
  691. static double FAR ltmin[2][SBLIMIT], lgmin[2][SBLIMIT], max_sc[2][SBLIMIT];
  692.     FLOAT snr32[32];
  693.     short sam[2][1056];
  694.     int whole_SpF, extra_slot = 0;
  695.     double avg_slots_per_frame, frac_SpF, slot_lag;
  696.     int model, stereo, error_protection;
  697. static unsigned int crc;
  698.     int i, j, k, adb;
  699.     unsigned long bitsPerSlot, samplesPerFrame, frameNum = 0;
  700.     unsigned long frameBits, sentBits = 0;
  701.     unsigned long num_samples;
  702.  
  703. #ifdef UNIX
  704.     clock_t time_to_encode = clock();
  705. #endif
  706.  
  707. #ifdef  MACINTOSH
  708.     console_options.nrows = MAC_WINDOW_SIZE;
  709.     argc = ccommand(&argv);
  710. #endif
  711.  
  712.  
  713.     /* Most large variables are declared dynamically to ensure
  714.        compatibility with smaller machines */
  715.  
  716.     sb_sample = (SBS FAR *) mem_alloc(sizeof(SBS), "sb_sample");
  717.     j_sample = (JSBS FAR *) mem_alloc(sizeof(JSBS), "j_sample");
  718.     win_que = (IN FAR *) mem_alloc(sizeof(IN), "Win_que");
  719.     subband = (SUB FAR *) mem_alloc(sizeof(SUB),"subband");
  720.     win_buf = (short FAR **) mem_alloc(sizeof(short *)*2, "win_buf");
  721.  
  722.     /* clear buffers */
  723.     memset((char *) buffer, 0, sizeof(buffer));
  724.     memset((char *) bit_alloc, 0, sizeof(bit_alloc));
  725.     memset((char *) scalar, 0, sizeof(scalar));
  726.     memset((char *) j_scale, 0, sizeof(j_scale));
  727.     memset((char *) scfsi, 0, sizeof(scfsi));
  728.     memset((char *) ltmin, 0, sizeof(ltmin));
  729.     memset((char *) lgmin, 0, sizeof(lgmin));
  730.     memset((char *) max_sc, 0, sizeof(max_sc));
  731.     memset((char *) snr32, 0, sizeof(snr32));
  732.     memset((char *) sam, 0, sizeof(sam));
  733.  
  734.     fr_ps.header = &info;
  735.     fr_ps.tab_num = -1;             /* no table loaded */
  736.     fr_ps.alloc = NULL;
  737.     info.version = MPEG_AUDIO_ID;
  738.  
  739.     programName = argv[0];
  740.     if(argc==1)     /* no command-line args */
  741.        obtain_parameters(&fr_ps, &model, &num_samples,
  742.                          original_file_name, encoded_file_name);
  743.     else
  744.        parse_args(argc, argv, &fr_ps, &model, &num_samples,
  745.                   original_file_name, encoded_file_name);
  746.     print_config(&fr_ps, &model, &num_samples,
  747.                  original_file_name, encoded_file_name);
  748.  
  749.     hdr_to_frps(&fr_ps);
  750.     stereo = fr_ps.stereo;
  751.     error_protection = info.error_protection;
  752.  
  753.     if (info.lay == 1) { bitsPerSlot = 32; samplesPerFrame = 384;  }
  754.     else               { bitsPerSlot = 8;  samplesPerFrame = 1152; }
  755.     /* Figure average number of 'slots' per frame. */
  756.     /* Bitrate means TOTAL for both channels, not per side. */
  757.     avg_slots_per_frame = ((double)samplesPerFrame /
  758.                            s_freq[info.sampling_frequency]) *
  759.                           ((double)bitrate[info.lay-1][info.bitrate_index] /
  760.                            (double)bitsPerSlot);
  761.     whole_SpF = (int) avg_slots_per_frame;
  762.     printf("slots/frame = %d\n",whole_SpF);
  763.     frac_SpF  = avg_slots_per_frame - (double)whole_SpF;
  764.     slot_lag  = -frac_SpF;
  765.     printf("frac SpF=%.3f, tot bitrate=%d kbps, s freq=%.1f kHz\n",
  766.            frac_SpF, bitrate[info.lay-1][info.bitrate_index],
  767.            s_freq[info.sampling_frequency]);
  768.  
  769.     if (frac_SpF != 0)
  770.        printf("Fractional number of slots, padding required\n");
  771.     else info.padding = 0;
  772.  
  773.     while (get_audio(musicin, buffer, num_samples, stereo, info.lay) > 0) {
  774.  
  775.        fprintf(stderr, "{%4lu}\r", frameNum++); fflush(stderr);
  776.        win_buf[0] = &buffer[0][0];
  777.        win_buf[1] = &buffer[1][0];
  778.        if (frac_SpF != 0) {
  779.           if (slot_lag > (frac_SpF-1.0) ) {
  780.              slot_lag -= frac_SpF;
  781.              extra_slot = 0;
  782.              info.padding = 0;
  783.              /*  printf("No padding for this frame\n"); */
  784.           }
  785.           else {
  786.              extra_slot = 1;
  787.              info.padding = 1;
  788.              slot_lag += (1-frac_SpF);
  789.              /*  printf("Padding for this frame\n");    */
  790.           }
  791.        }
  792.        adb = (whole_SpF+extra_slot) * bitsPerSlot;
  793.  
  794.        switch (info.lay) {
  795.  
  796. /***************************** Layer I **********************************/
  797.  
  798.           case 1 :
  799.              for (j=0;j<SCALE_BLOCK;j++)
  800.              for (k=0;k<stereo;k++) {
  801.                 window_subband(&win_buf[k], &(*win_que)[k][0], k);
  802.                 filter_subband(&(*win_que)[k][0], &(*sb_sample)[k][0][j][0]);
  803.              }
  804.  
  805.              I_scale_factor_calc(*sb_sample, scalar, stereo);
  806.              if(fr_ps.actual_mode == MPG_MD_JOINT_STEREO) {
  807.                 I_combine_LR(*sb_sample, *j_sample);
  808.                 I_scale_factor_calc(j_sample, &j_scale, 1);
  809.              }
  810.  
  811.              put_scale(scalar, &fr_ps, max_sc);
  812.  
  813.              if (model == 1) I_Psycho_One(buffer, max_sc, ltmin, &fr_ps);
  814.              else {
  815.                 for (k=0;k<stereo;k++) {
  816.                    psycho_anal(&buffer[k][0],&sam[k][0], k, info.lay, snr32,
  817.                                (FLOAT)s_freq[info.sampling_frequency]*1000);
  818.                    for (i=0;i<SBLIMIT;i++) ltmin[k][i] = (double) snr32[i];
  819.                 }
  820.              }
  821.  
  822.              I_main_bit_allocation(ltmin, bit_alloc, &adb, &fr_ps);
  823.  
  824.              if (error_protection) I_CRC_calc(&fr_ps, bit_alloc, &crc);
  825.  
  826.              encode_info(&fr_ps, &bs);
  827.  
  828.              if (error_protection) encode_CRC(crc, &bs);
  829.  
  830.              I_encode_bit_alloc(bit_alloc, &fr_ps, &bs);
  831.              I_encode_scale(scalar, bit_alloc, &fr_ps, &bs);
  832.              I_subband_quantization(scalar, *sb_sample, j_scale, *j_sample,
  833.                                     bit_alloc, *subband, &fr_ps);
  834.              I_sample_encoding(*subband, bit_alloc, &fr_ps, &bs);
  835.              for (i=0;i<adb;i++) put1bit(&bs, 0);
  836.           break;
  837.  
  838. /***************************** Layer 2 **********************************/
  839.  
  840.           case 2 :
  841.              for (i=0;i<3;i++) for (j=0;j<SCALE_BLOCK;j++)
  842.                 for (k=0;k<stereo;k++) {
  843.                    window_subband(&win_buf[k], &(*win_que)[k][0], k);
  844.                    filter_subband(&(*win_que)[k][0], &(*sb_sample)[k][i][j][0]);
  845.                 }
  846.  
  847.                 II_scale_factor_calc(*sb_sample, scalar, stereo, fr_ps.sblimit);
  848.                 pick_scale(scalar, &fr_ps, max_sc);
  849.                 if(fr_ps.actual_mode == MPG_MD_JOINT_STEREO) {
  850.                    II_combine_LR(*sb_sample, *j_sample, fr_ps.sblimit);
  851.                    II_scale_factor_calc(j_sample, &j_scale, 1, fr_ps.sblimit);
  852.                 }       /* this way we calculate more mono than we need */
  853.                         /* but it is cheap */
  854.  
  855.                 if (model == 1) II_Psycho_One(buffer, max_sc, ltmin, &fr_ps);
  856.                 else {
  857.                    for (k=0;k<stereo;k++) {
  858.                       psycho_anal(&buffer[k][0],&sam[k][0], k, 
  859.                                  info.lay, snr32,
  860.                                  (FLOAT)s_freq[info.sampling_frequency]*1000);
  861.                       for (i=0;i<SBLIMIT;i++) ltmin[k][i] = (double) snr32[i];
  862.                    }
  863.                 }
  864.  
  865.                 II_transmission_pattern(scalar, scfsi, &fr_ps);
  866.                 II_main_bit_allocation(ltmin, scfsi, bit_alloc, &adb, &fr_ps);
  867.  
  868.                 if (error_protection)
  869.                    II_CRC_calc(&fr_ps, bit_alloc, scfsi, &crc);
  870.  
  871.                 encode_info(&fr_ps, &bs);
  872.  
  873.                 if (error_protection) encode_CRC(crc, &bs);
  874.  
  875.                 II_encode_bit_alloc(bit_alloc, &fr_ps, &bs);
  876.                 II_encode_scale(bit_alloc, scfsi, scalar, &fr_ps, &bs);
  877.                 II_subband_quantization(scalar, *sb_sample, j_scale,
  878.                                       *j_sample, bit_alloc, *subband, &fr_ps);
  879.                 II_sample_encoding(*subband, bit_alloc, &fr_ps, &bs);
  880.                 for (i=0;i<adb;i++) put1bit(&bs, 0);
  881.           break;
  882.  
  883. /***************************** Layer 3 **********************************/
  884.  
  885.           case 3 : break;
  886.  
  887.        }
  888.  
  889.        frameBits = sstell(&bs) - sentBits;
  890.        if(frameBits%bitsPerSlot)   /* a program failure */
  891.           fprintf(stderr,"Sent %ld bits = %ld slots plus %ld\n",
  892.                   frameBits, frameBits/bitsPerSlot,
  893.                   frameBits%bitsPerSlot);
  894.        sentBits += frameBits;
  895.  
  896.     }
  897.  
  898.     close_bit_stream_w(&bs);
  899.  
  900.     printf("Avg slots/frame = %.3f; b/smp = %.2f; br = %.3f kbps\n",
  901.            (FLOAT) sentBits / (frameNum * bitsPerSlot),
  902.            (FLOAT) sentBits / (frameNum * samplesPerFrame),
  903.            (FLOAT) sentBits / (frameNum * samplesPerFrame) *
  904.            s_freq[info.sampling_frequency]);
  905.  
  906.     if (fclose(musicin) != 0){
  907.        printf("Could not close \"%s\".\n", original_file_name);
  908.        exit(2);
  909.     }
  910.  
  911. #ifdef  MACINTOSH
  912.     set_mac_file_attr(encoded_file_name, VOL_REF_NUM, CREATOR_ENCODE,
  913.                       FILETYPE_ENCODE);
  914. #endif
  915.  
  916.     printf("Encoding of \"%s\" with psychoacoustic model %d is finished\n",
  917.            original_file_name, model);
  918.     printf("The MPEG encoded output file name is \"%s\"\n",
  919.             encoded_file_name);
  920.  
  921. #ifdef UNIX
  922.     time_to_encode = clock()-time_to_encode;
  923.  
  924.     printf("Total time used to encode the stream was %.2f secs.\n",
  925.     (float)time_to_encode/CLK_TCK);
  926. #endif
  927.  
  928.     exit(0);
  929. }
  930.  
  931. /************************************************************************
  932. /*
  933. /* usage
  934. /*
  935. /* PURPOSE:  Writes command line syntax to the file specified by #stderr#
  936. /*
  937. /************************************************************************/
  938.  
  939. static void usage()  /* print syntax & exit */
  940. {
  941.     fprintf(stderr,
  942.     "usage: %s                         queries for all arguments, or\n",
  943.             programName);
  944.     fprintf(stderr,
  945.     "       %s [-l lay][-m mode][-p psy][-s sfrq][-b br][-d emp]\n",
  946.             programName);
  947.     fprintf(stderr,
  948.     "          [-c][-o][-e] inputPCM [outBS]\n");
  949.     fprintf(stderr,"where\n");
  950.     fprintf(stderr," -l lay   use layer <lay> coding   (dflt %4u)\n",DFLT_LAY);
  951.     fprintf(stderr," -m mode  channel mode : s/d/j/m   (dflt %4c)\n",DFLT_MOD);
  952.     fprintf(stderr," -p psy   psychoacoustic model 1/2 (dflt %4u)\n",DFLT_PSY);
  953.     fprintf(stderr," -s sfrq  input smpl rate in kHz   (dflt %4.1f)\n",DFLT_SFQ);
  954.     fprintf(stderr," -b br    total bitrate in kbps    (dflt %4u)\n",DFLT_BRT);
  955.     fprintf(stderr," -d emp   de-emphasis n/5/c        (dflt %4c)\n",DFLT_EMP);
  956.     fprintf(stderr," -c       mark as copyright\n");
  957.     fprintf(stderr," -o       mark as original\n");
  958.     fprintf(stderr," -e       add error protection\n");
  959.     fprintf(stderr," inputPCM input PCM sound file (standard or AIFF)\n");
  960.     fprintf(stderr," outBS    output bit stream of encoded audio (dflt inName+%s)\n",
  961.             DFLT_EXT);
  962.     exit(1);
  963. }
  964.  
  965. /************************************************************************
  966. /*
  967. /* aiff_check
  968. /*
  969. /* PURPOSE:  Checks AIFF header information to make sure it is valid.
  970. /*           Exits if not.
  971. /*
  972. /************************************************************************/
  973.  
  974. void aiff_check(file_name, pcm_aiff_data)
  975. char *file_name;          /* Pointer to name of AIFF file */
  976. IFF_AIFF *pcm_aiff_data;  /* Pointer to AIFF data structure */
  977. {
  978.  
  979. #ifdef IFF_LONG
  980.     if (pcm_aiff_data->sampleType != IFF_ID_SSND) {
  981. #else
  982.     if (strncmp(&pcm_aiff_data->sampleType,IFF_ID_SSND,4)) {
  983. #endif
  984.        printf("Sound data is not PCM in \"%s\".\n", file_name);
  985.        exit(1);
  986.     }
  987.  
  988.     if(SmpFrqIndex((long)pcm_aiff_data->sampleRate) < 0) {
  989.        printf("in \"%s\".\n", file_name);
  990.        exit(1);
  991.     }
  992.  
  993.     if (pcm_aiff_data->sampleSize != sizeof(short) * BITS_IN_A_BYTE) {
  994.         printf("Sound data is not %d bits in \"%s\".\n",
  995.                sizeof(short) * BITS_IN_A_BYTE, file_name);
  996.         exit(1);
  997.     }
  998.  
  999.     if (pcm_aiff_data->numChannels != MONO &&
  1000.         pcm_aiff_data->numChannels != STEREO) {
  1001.        printf("Sound data is not mono or stereo in \"%s\".\n", file_name);
  1002.        exit(1);
  1003.     }
  1004.  
  1005.     if (pcm_aiff_data->blkAlgn.blockSize != 0) {
  1006.        printf("Block size is not %lu bytes in \"%s\".\n", 0, file_name);
  1007.        exit(1);
  1008.     }
  1009.  
  1010.     if (pcm_aiff_data->blkAlgn.offset != 0) {
  1011.        printf("Block offset is not %lu bytes in \"%s\".\n", 0, file_name);
  1012.        exit(1);
  1013.     }
  1014.  
  1015. }
  1016.